<template>
  <div class="mistake-book-container">
    <el-card class="mistake-list" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>我的错题本</span>
          <div class="header-right">
            <el-select v-model="filterType" placeholder="题型筛选" clearable class="filter-select">
              <el-option label="全部题型" value="" />
              <el-option label="选择题" :value="1" />
              <el-option label="填空题" :value="2" />
              <el-option label="简答题" :value="3" />
              <el-option label="综合题" :value="4" />
            </el-select>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索题目内容"
              clearable
              class="search-input"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <!-- 添加知识点统计卡片 -->
      <el-card class="knowledge-stats" v-if="knowledgeStats.length > 0">
        <template #header>
          <div class="stats-header">
            <span>知识点统计</span>
          </div>
        </template>
        <div class="stats-content">
          <el-row :gutter="20">
            <el-col :span="8" v-for="stat in knowledgeStats" :key="stat.knowledge_point_id">
              <el-card class="stat-card" shadow="hover">
                <div class="stat-title">
                  <el-tag type="success" effect="plain">{{ stat.knowledge_point_name }}</el-tag>
                </div>
                <div class="stat-info">
                  <p class="stat-desc">{{ stat.knowledge_point_description }}</p>
                  <div class="stat-numbers">
                    <div class="stat-item">
                      <span class="label">错题数：</span>
                      <span class="value">{{ stat.mistake_count }}</span>
                    </div>
                    <div class="stat-item">
                      <span class="label">重做次数：</span>
                      <span class="value">{{ stat.total_retry_count }}</span>
                    </div>
                    <div class="stat-item">
                      <span class="label">正确次数：</span>
                      <span class="value">{{ stat.total_correct_count }}</span>
                    </div>
                    <div class="stat-item">
                      <span class="label">正确率：</span>
                      <span class="value">{{ calculateCorrectRate(stat) }}%</span>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <el-empty v-if="filteredMistakes.length === 0" description="暂无错题记录" />
      
      <div v-else class="mistake-items">
        <el-collapse v-model="activeNames">
          <el-collapse-item v-for="mistake in filteredMistakes" 
                           :key="mistake.id" 
                           :name="mistake.id">
            <template #title>
              <div class="mistake-header">
                <span class="question-type">
                  {{ getQuestionTypeText(mistake.questionType) }}
                </span>
                <span class="score">得分：{{ mistake.score }}/{{ mistake.maxScore }}</span>
                <span class="retry-info">
                  重做：{{ mistake.retryCount || 0 }}次
                  <el-tooltip content="重做正确次数" placement="top">
                    <span class="correct-count">(正确{{ mistake.correctCount || 0 }}次)</span>
                  </el-tooltip>
                </span>
                <span class="date">{{ formatDate(mistake.createTime) }}</span>
              </div>
            </template>

            <div class="question-content">
              <h4>题目内容：</h4>
              <p>{{ mistake.questionContent }}</p>

              <!-- 添加知识点显示 -->
              <div v-if="mistake.knowledgePointId" class="knowledge-point-info">
                <el-tag type="success" effect="plain">
                  相关知识点：{{ mistake.knowledgePointName }}
                </el-tag>
                <p class="knowledge-point-desc">{{ mistake.knowledgePointDescription }}</p>
              </div>

              <!-- 选择题选项 -->
              <template v-if="mistake.questionType === 1 && mistake.questionOptions">
                <div class="options-list">
                  <p v-for="(option, index) in parseOptions(mistake.questionOptions)" 
                     :key="index"
                     :class="{
                       'correct-option': isCorrectOption(mistake, index),
                       'wrong-option': isWrongOption(mistake, index)
                     }">
                    {{ String.fromCharCode(65 + index) }}. {{ option.content }}
                  </p>
                </div>
              </template>

              <div class="answer-section">
                <div class="student-answer">
                  <h5>你的答案：</h5>
                  <p :class="{'wrong-answer': true}">{{ mistake.studentAnswer }}</p>
                </div>
                <div class="standard-answer">
                  <h5>标准答案：</h5>
                  <p :class="{'correct-answer': true}">{{ mistake.standardAnswer }}</p>
                </div>
                <div class="teacher-comment" v-if="mistake.teacherComment">
                  <h5>教师评语：</h5>
                  <p>{{ mistake.teacherComment }}</p>
                </div>
              </div>

              <div class="operations">
                <el-button type="primary" @click="handleRetry(mistake)">重做此题</el-button>
                <el-button type="danger" @click="handleDelete(mistake)">从错题本中移除</el-button>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-card>

    <!-- 重做对话框 -->
    <el-dialog
      v-model="retryDialogVisible"
      :title="'重做题目'"
      width="60%"
    >
      <template v-if="currentMistake">
        <div class="retry-content">
          <h4>{{ currentMistake.questionContent }}</h4>
          
          <!-- 选择题 -->
          <template v-if="currentMistake.questionType === 1">
            <el-radio-group v-model="retryAnswer">
              <div v-for="(option, index) in parseOptions(currentMistake.questionOptions)" 
                   :key="index" 
                   class="option-item">
                <el-radio :label="String.fromCharCode(65 + index)">
                  {{ option.content }}
                </el-radio>
              </div>
            </el-radio-group>
          </template>

          <!-- 填空题 -->
          <template v-else-if="currentMistake.questionType === 2">
            <el-input v-model="retryAnswer" placeholder="请输入答案" />
          </template>

          <!-- 简答题或综合题 -->
          <template v-else>
            <el-input
              v-model="retryAnswer"
              type="textarea"
              :rows="4"
              placeholder="请输入答案"
            />
          </template>
        </div>
      </template>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="retryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRetry">提交答案</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 答案对比对话框 -->
    <el-dialog
      v-model="compareDialogVisible"
      title="答案对比"
      width="60%"
    >
      <template v-if="currentMistake">
        <div class="compare-content">
          <h4>{{ currentMistake.questionContent }}</h4>
          
          <div class="answer-comparison">
            <div class="retry-answer">
              <h5>本次答案：</h5>
              <p :class="{'correct-answer': isRetryCorrect, 'wrong-answer': !isRetryCorrect}">
                {{ retryAnswer }}
              </p>
            </div>
            <div class="standard-answer">
              <h5>标准答案：</h5>
              <p class="correct-answer">{{ currentMistake.standardAnswer }}</p>
            </div>
          </div>

          <div class="result-message" :class="{'success': isRetryCorrect, 'error': !isRetryCorrect}">
            <el-icon v-if="isRetryCorrect"><CircleCheckFilled /></el-icon>
            <el-icon v-else><CircleCloseFilled /></el-icon>
            {{ isRetryCorrect ? '恭喜你答对了！' : '再接再厉！' }}
          </div>
        </div>
      </template>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="compareDialogVisible = false">关闭</el-button>
          <el-button v-if="!isRetryCorrect" type="primary" @click="handleRetry(currentMistake)">
            再试一次
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import useUserInfoStore from '@/stores/userInfo'
import { getStudentMistakes, deleteMistake, updateMistake, updateRetryCount, getKnowledgeStats } from '@/api/mistakeBook'
import { Search, Delete, Document, CircleCheckFilled, CircleCloseFilled } from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserInfoStore()
const loading = ref(false)
const mistakes = ref([])
const activeNames = ref([])
const filterType = ref('')
const searchKeyword = ref('')
const retryDialogVisible = ref(false)
const compareDialogVisible = ref(false)
const currentMistake = ref(null)
const retryAnswer = ref('')
const isRetryCorrect = ref(false)
const knowledgeStats = ref([])

// 根据题型和关键词筛选错题
const filteredMistakes = computed(() => {
  let result = mistakes.value

  // 按题型筛选
  if (filterType.value) {
    result = result.filter(m => m.questionType === filterType.value)
  }

  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(m => 
      m.questionContent.toLowerCase().includes(keyword) ||
      m.studentAnswer.toLowerCase().includes(keyword) ||
      m.standardAnswer.toLowerCase().includes(keyword) ||
      (m.teacherComment && m.teacherComment.toLowerCase().includes(keyword))
    )
  }

  return result
})

// 获取错题列表
const fetchMistakes = async () => {
  try {
    loading.value = true
    const res = await getStudentMistakes(userStore.info.id)
    mistakes.value = res.data
  } catch (error) {
    console.error('获取错题列表失败:', error)
    ElMessage.error('获取错题列表失败')
  } finally {
    loading.value = false
  }
}

// 解析选择题选项
const parseOptions = (optionsStr) => {
  try {
    return JSON.parse(optionsStr)
  } catch {
    return []
  }
}

// 判断是否是正确选项
const isCorrectOption = (mistake, index) => {
  const optionLetter = String.fromCharCode(65 + index)
  return mistake.standardAnswer === optionLetter
}

// 判断是否是错误选项
const isWrongOption = (mistake, index) => {
  const optionLetter = String.fromCharCode(65 + index)
  return mistake.studentAnswer === optionLetter && mistake.studentAnswer !== mistake.standardAnswer
}

// 获取题型文本
const getQuestionTypeText = (type) => {
  const types = {
    1: '选择题',
    2: '填空题',
    3: '简答题',
    4: '综合题'
  }
  return types[type] || '未知题型'
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 重做题目
const handleRetry = (mistake) => {
  currentMistake.value = mistake
  retryAnswer.value = ''
  retryDialogVisible.value = true
  compareDialogVisible.value = false
}

// 提交重做答案
const submitRetry = async () => {
  if (!retryAnswer.value) {
    ElMessage.warning('请输入答案')
    return
  }

  try {
    // 检查答案是否正确
    if (currentMistake.value.questionType === 1) {
      // 选择题直接比较答案
      isRetryCorrect.value = retryAnswer.value === currentMistake.value.standardAnswer
    } else {
      // 其他题型，去除空格后比较
      isRetryCorrect.value = retryAnswer.value.trim() === currentMistake.value.standardAnswer.trim()
    }

    console.log('准备更新重做次数:', {
      mistakeId: currentMistake.value.id,
      isCorrect: isRetryCorrect.value,
      currentRetryCount: currentMistake.value.retryCount,
      currentCorrectCount: currentMistake.value.correctCount
    })

    // 更新重做次数
    const response = await updateRetryCount(currentMistake.value.id, isRetryCorrect.value)
    console.log('更新重做次数响应:', response)
    
    // 更新本地数据
    const mistake = mistakes.value.find(m => m.id === currentMistake.value.id)
    if (mistake) {
      console.log('更新前的数据:', {
        retryCount: mistake.retryCount,
        correctCount: mistake.correctCount
      })
      
      mistake.retryCount = (mistake.retryCount || 0) + 1
      if (isRetryCorrect.value) {
        mistake.correctCount = (mistake.correctCount || 0) + 1
      }

      console.log('更新后的数据:', {
        retryCount: mistake.retryCount,
        correctCount: mistake.correctCount
      })
    }

    // 显示对比对话框
    retryDialogVisible.value = false
    compareDialogVisible.value = true

    // 如果答对了，询问是否从错题本中移除
    if (isRetryCorrect.value) {
      ElMessageBox.confirm(
        '恭喜你答对了！是否要从错题本中移除这道题目？',
        '提示',
        {
          confirmButtonText: '移除',
          cancelButtonText: '保留',
          type: 'success'
        }
      ).then(() => {
        handleDelete(currentMistake.value)
      }).catch(() => {
        // 用户选择保留，不做任何操作
      })
    }
  } catch (error) {
    console.error('更新重做记录失败:', error)
    console.error('错误详情:', {
      mistakeId: currentMistake.value?.id,
      isCorrect: isRetryCorrect.value,
      error: error.message,
      response: error.response?.data
    })
    ElMessage.error('更新重做记录失败：' + (error.response?.data?.message || error.message))
  }
}

// 删除错题
const handleDelete = async (mistake) => {
  try {
    await ElMessageBox.confirm(
      '确定要从错题本中移除这道题目吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteMistake(mistake.id)
    ElMessage.success('已从错题本中移除')
    mistakes.value = mistakes.value.filter(m => m.id !== mistake.id)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除错题失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 检查用户权限
const checkAuth = async () => {
  if (!userStore.info) {
    await userStore.getUserInfo()
  }
  
  if (!userStore.info || userStore.info.role !== 0) {
    ElMessage.error('只有学生可以访问错题本')
    router.push('/home')
    return false
  }
  return true
}

// 获取知识点统计
const fetchKnowledgeStats = async () => {
  try {
    const res = await getKnowledgeStats(userStore.info.id)
    knowledgeStats.value = res.data
  } catch (error) {
    console.error('获取知识点统计失败:', error)
    ElMessage.error('获取知识点统计失败')
  }
}

// 计算正确率
const calculateCorrectRate = (stat) => {
  if (!stat.total_retry_count) return 0
  return Math.round((stat.total_correct_count / stat.total_retry_count) * 100)
}

onMounted(async () => {
  if (await checkAuth()) {
    fetchMistakes()
    fetchKnowledgeStats()
  }
})
</script>

<style scoped>
.mistake-book-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-right {
  display: flex;
  gap: 15px;
}

.filter-select {
  width: 120px;
}

.search-input {
  width: 200px;
}

.mistake-items {
  margin-top: 20px;
}

.mistake-header {
  display: flex;
  align-items: center;
  gap: 20px;
}

.question-type {
  background-color: #409EFF;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.score {
  color: #F56C6C;
  font-weight: bold;
}

.retry-info {
  color: #409EFF;
  font-size: 14px;
}

.correct-count {
  color: #67C23A;
  margin-left: 4px;
}

.date {
  color: #909399;
  font-size: 14px;
}

.question-content {
  margin: 20px 0;
}

.question-content h4 {
  margin-bottom: 10px;
  color: #303133;
}

.options-list {
  margin: 10px 0;
  padding-left: 20px;
}

.correct-option {
  color: #67C23A;
  font-weight: bold;
}

.wrong-option {
  color: #F56C6C;
  text-decoration: line-through;
}

.answer-section {
  margin: 20px 0;
}

.student-answer, .standard-answer, .teacher-comment {
  margin: 10px 0;
  padding: 10px;
  border-radius: 4px;
}

.student-answer {
  background-color: #FFF;
}

.standard-answer {
  background-color: #F0F9EB;
}

.teacher-comment {
  background-color: #FDF6EC;
}

.student-answer h5, .standard-answer h5, .teacher-comment h5 {
  color: #606266;
  margin-bottom: 5px;
}

.wrong-answer {
  color: #F56C6C;
}

.correct-answer {
  color: #67C23A;
}

.operations {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

:deep(.el-collapse-item__header) {
  font-size: 16px;
}

:deep(.el-collapse-item__content) {
  padding: 20px;
}

.retry-content {
  padding: 20px;
}

.option-item {
  margin: 10px 0;
}

.answer-comparison {
  margin: 20px 0;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.retry-answer, .standard-answer {
  margin: 10px 0;
}

.retry-answer h5, .standard-answer h5 {
  color: #606266;
  margin-bottom: 5px;
}

.result-message {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 20px 0;
  padding: 10px;
  border-radius: 4px;
  font-size: 16px;
}

.result-message.success {
  background-color: #f0f9eb;
  color: #67C23A;
}

.result-message.error {
  background-color: #fef0f0;
  color: #F56C6C;
}

.result-message .el-icon {
  margin-right: 8px;
  font-size: 20px;
}

.knowledge-point-info {
  margin: 10px 0;
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
}

.knowledge-point-desc {
  margin: 8px 0 0 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
}

.knowledge-stats {
  margin-bottom: 20px;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats-content {
  margin-top: 20px;
}

.stat-card {
  margin-bottom: 20px;
}

.stat-title {
  margin-bottom: 10px;
}

.stat-desc {
  color: #606266;
  font-size: 14px;
  margin-bottom: 15px;
  line-height: 1.4;
}

.stat-numbers {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.stat-item .label {
  color: #909399;
  font-size: 14px;
}

.stat-item .value {
  color: #303133;
  font-weight: bold;
}
</style> 